﻿using Microsoft.EntityFrameworkCore;
using ProgrammingEducationSystem.DbConfig;
using ProgrammingEducationSystem.Models;
using System.Linq;

namespace ProgrammingEducationSystem.Repository.IRepository
{
    public class CourseHourRepository : BaseRepository<CourseHour>, ICourseHourRepository
    {
        public CourseHourRepository(AppDbCtx appDbCtx) : base(appDbCtx)
        {
        }


        public async Task<List<CourseHour>> GetByClassIdAsync(Guid classId)
        {
            var @class =  _appDbCtx.Classes
                .Include(c => c.courses)
                .ThenInclude(cr => cr.courseHours)
                .Where(c => c.Id == classId).FirstOrDefault();
            if (@class == null)
            {
                return new List<CourseHour>();
            }

            var courses = @class.courses;
            List<CourseHour> chs = new List<CourseHour>();
            courses.ForEach(c =>
            {
                chs.AddRange(c.courseHours);
            });
            return chs;
        }

        public async Task<List<CourseHour>> GetByClassRoomIdAsync(Guid classRoomId)
        {
            return await _appDbCtx.CourseHours
            .Where(ch => ch.ClassRoomId == classRoomId)
            .ToListAsync();
        }

        public async Task<List<CourseHour>> GetByStuIdAsync(string stuId)
        {
            var classIds = await _appDbCtx.StuAndClasses
            .Where(sc => sc.StudentId == stuId)
            .Select(sa => sa.ClassId)
            .ToListAsync();
            return await _appDbCtx.CourseHours
            .Include(ch => ch.Course)
            .ThenInclude(c => c.@class)
            .Where(ch => classIds.Contains(ch.Course.ClassId))
            .ToListAsync();
        }

        public async Task<List<CourseHour>> GetByTeaIdAsync(string teaId)
        {
            return await _appDbCtx.CourseHours
            .Include(ch => ch.Course)
            .ThenInclude(c => c.@class)
            .Where(ch => ch.Course.@class.TeacherId == teaId)
            .ToListAsync();
        }
    }
}
